﻿$(document).ready(function() {
    $('a').click(function() {
        var ID = $(this).attr("id").toString();
        $.ajax({
            type: 'GET',
            url: '/Views/ClientTaskView.ashx',
            data: { 'eventView': 'StartTask', 'params': "{id:" + ID + "}" },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: initTimerCount(ID)
        });
    });
});

function endTask() {
    var ID = $("[id$=TarefaCorrente]").val();
    $.ajax({
        type: 'GET',
        url: '/Views/ClientTaskView.ashx',
        data: { 'eventView': 'EndTask', 'params': "{id:" + ID + "}" },
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: sucessTask()
    });    
}

var timer;
function initTimerCount(ID) {
    $("[id$=TarefaCorrente]").val(ID);
    timer = setInterval('countDown()', 1000);
}

function countDown() {
    var currentTime = $('#Timer').text().trim();
    $('#Timer').text(calcCorrectTime(currentTime));

    if ($('#Timer').text() == '0') {
        clearInterval(timer);
        endTask();
    }
}

function sucessTask() {
    $("[id$=Timer]").val('');
    alert('Tarefa Finalizada');
}

function calcCorrectTime(currentTime) {
    var time = null;
    var minutes = 0;
    var seconds = 0;
    var milliseconds = null;
    
    if (currentTime == ''){
        minutes = 1;
    }else{
        var mm_ss = currentTime.split(":");
        minutes = parseInt(mm_ss[0]);
        seconds = parseInt(mm_ss[1]);
    }

    if (minutes <= 0 && seconds <= 0)
        return '0';
    
    time = new Date(0, 0, 0, 0, minutes, seconds, 0);
    milliseconds = ((time.getMinutes() * 60000) + (seconds * 1000)) - 1;
    time = new Date(milliseconds);
    
    return time.getMinutes().toString() + ':' + time.getSeconds().toString();
}